import { auditSchedule, handleSender, cancelPress, getToggleInfo } from '@/api/legal';
import { getHistoryDetail } from '@/api/process';
import { isJSON } from '@/utils/tools';
import { encryption } from '@/utils';
import DingDingDialog from '@/components/Customer/detail/dialog';
import { showModal } from '@/utils/message';
import { BUSINESS_TYPE } from '@/utils/const/process';

export default {
  components: {
    DingDingDialog
  },
  data() {
    return {
      auditScheduleData: {},
      senders: [],
      explanationObj: {
        content: '',
        styConfig: ''
      },
      currentNodeId: '',
      pressDefaultList: [],
      currentProcessIndex: -1,
      modifyNodeId: '',
      scheduleId: '', // 重新获取审批进度数据id
      version: '', // 详情当前版本
      isCurrentVersion: true // 是否是当前版本
    };
  },
  computed: {
    toggleKeyName() {
      return this.$route.name + '_toggleKey';
    },
    sessionCacheKey() {
      return sessionStorage.getItem(this.toggleKeyName) || null;
    }
  },
  watch: {
    progressType(val) {
      val === 1 && this.scheduleId && this.requestAuditSchedule(this.scheduleId);
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.sessionCacheKey) {
      sessionStorage.removeItem(this.toggleKeyName);
    }
    next();
  },
  methods: {
    isJSON,
    requestAuditSchedule(id) {
      if (!id && id !== 0) return;
      this.scheduleId = id;
      auditSchedule(id).then(res => {
        if (res.code === 200) {
          this.auditScheduleData = res.data && res.data.auditInfo;
          this.senders = res.data && res.data.auditInfo && res.data.auditInfo.senders || [];
          if ((res.data.isRedirectTimeOut || res.data.transferFlag) && this.auditScheduleData.process && this.auditScheduleData.process.length > 0) {
            const len = this.auditScheduleData.process.length;
            for (let i = 0; i < len; i++) {
              // 审批状态为进行中
              const currentNode = this.auditScheduleData.process[i];
              if (currentNode.nodeStatus === 1) {
                this.explanationObj.countdownOver = currentNode.countdownOver;
                this.explanationObj.countdown = currentNode.approvalEndTime - currentNode.serverTime;
                break;
              }
            }
          }
          if (res.data.styConfig && this.isJSON(res.data.styConfig)) {
            res.data.styConfig = JSON.parse(res.data.styConfig);
            res.data.styConfig.padding = '8px 9px';
          } else {
            res.data.styConfig = {};
            res.data.styConfig.padding = '8px 9px';
          }
          const obj = {
            content: res.data.explanation || '',
            styConfig: JSON.stringify(res.data.styConfig) || '',
            isRedirectTimeOut: res.data.isRedirectTimeOut || 0,
            transferRemark: res.data.transferRemark || '',
            transferNodeId: res.data.transferNodeId || null,
            transferFlag: res.data.transferFlag
          };
          this.explanationObj = {
            ...this.explanationObj,
            ...obj
          };
          const modifyNode = this.auditScheduleData.process.find(el => el.nodeStatus === 1) || {};
          this.currentProcessIndex = this.auditScheduleData.process.findIndex(el => el.nodeStatus === 1);
          this.modifyNodeId = modifyNode.id;
          this.version = res.data.version;
        }
      });
    },
    handlePressSend() {
      const currentNode = this.auditScheduleData.process.find(el => el.nodeStatus === 1) || {};
      const defaultUser = [];
      if (currentNode.examineRoles && currentNode.examineRoles.length) {
        currentNode.examineRoles.forEach(i => {
          i.aduitors.forEach(j => {
            if (!defaultUser.find(k => k.id === j.id)) {
              defaultUser.push(j);
            }
          });
        });
      }
      this.pressDefaultList = defaultUser;
      this.pressSend(defaultUser, currentNode);
    },
    handleCancelPress() {
      showModal('请确认是否取消加急').then(_ => {
        const id = this.processId || this.scheduleId;
        cancelPress({ id }).then(res => {
          if (res.code === 200) {
            this.$message.success('取消加急成功');
            this.queryProcessData();
          }
        }).catch(err => {
          console.log(err);
        });
      });
    },
    // 展示催办弹窗
    pressSend(defaultUser, struct) {
      this.currentNodeId = struct.id;
      const msg = '';
      this.$refs.pressSendDialogRef.showDialog({
        defaultMsg: msg,
        defaultUser
      });
    },
    toSend(data) {
      // 添加钉钉通知配置
      const postData = Object.assign(data, { id: this.currentNodeId });
      if (this.$refs.examineAndApproveRef) {
        this.$refs.examineAndApproveRef.pressSendMsg(postData);
        return;
      }
      this.pressSendMsg(postData);
    },
    // 再次发起（复制）
    handleCreateNew(routeName = '', params = {}, query = {}) {
      query.createNew = 1;
      const routeUrl = this.$router.resolve({
        name: routeName,
        params,
        query
      });
      window.open(routeUrl.href, '_blank');
    },
    // 审批流抄送
    handleSendMsg() {
      if (Array.isArray(this.multipleSelectionAll)) {
        const orderList = Array.isArray(this.list) ? this.list : (this.list && this.list.items || []);
        const selectData = this.multipleSelectionAll.length ? this.multipleSelectionAll : orderList;
        if (!selectData || !selectData.length) {
          this.$message.warning('暂无可抄送审批单');
          return;
        }
      }
      if (this.$refs.examineAndApproveRef) {
        this.$refs['examineAndApproveRef'].openAuditorDialog();
        return;
      }
      this.$refs['auditorDialog'].initSelectSender();
    },
    handleSender(selectUser = []) {
      handleSender({ processIds: this.scheduleId, sender: selectUser }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.requestAuditSchedule(this.scheduleId);
        if (this.$refs.examineAndApproveRef) {
          this.$refs.examineAndApproveRef.getProcessList();
        } else if (this.workFlowId) { // 供应商结算
          this.getProcessList(this.workFlowId);
        } else {
          this.getProcessList();
        }
        this.$message.success('抄送成功');
      }).catch(err => {
        console.log(err);
        this.$message.error(err.message);
      });
    },
    handleBatchSender(selectUser = [], items = this.list.items) {
      const field = this.$route.name === 'supplier' ? 'workFlowId' : 'processId';
      const selectData = this.multipleSelectionAll.length ? this.multipleSelectionAll : items;
      if (!selectData || !selectData.length) {
        this.$message.warning('暂无可抄送审批单');
        return;
      }
      const arr = [];
      selectData.map(it => {
        if (it[field]) arr.push(it[field]);
      });
      const processIds = arr.join(',');
      const params = {
        processIds,
        sender: selectUser
      };
      if (this.$route.name === 'supplier') {
        params.dataType = this.dimension ? 2 : 1;
      }
      if (arr.length) {
        handleSender(params).then(res => {
          if (res.code === 200) {
            this.$message.success('抄送成功');
          }
        }).catch(err => {
          if (err.code === 502 && (err.message.includes('审批单你没有抄送权限') || err.message.includes('流程不存在'))) {
            const returnMsgList = err.message.split('\r\n');
            const newDatas = [];
            const h = this.$createElement;
            for (const i in returnMsgList) {
              newDatas.push(h('p', { style: 'margin-bottom: 5px' }, returnMsgList[i]));
            }
            this.$message({
              showClose: true,
              message: h('div', { class: 'el-message__content' }, newDatas),
              customClass: 'multi-message-box',
              duration: 10000,
              type: 'warning'
            });
          } else {
            this.$message.error(err.message);
          }
        });
      } else {
        this.$message.warning('草稿中审批单无法抄送');
      }
    },
    // 修改跳转
    handleModify(routeName, params, query) {
      query.isModifyForm = 1;
      query.currentProcessIndex = this.currentProcessIndex;
      query.modifyNodeId = this.modifyNodeId;
      this.$router.push({
        name: routeName,
        params,
        query
      });
    },
    // 获取固定表单详情历史快照数据
    getHistoryDetail(id, approvalModuleType) {
      const key = this.loadingKeyMap(approvalModuleType);
      this[key] = true;
      getHistoryDetail({ id }).then(res => {
        this[key] = false;
        this.handleDetailData(res);
      }).catch(err => {
        this[key] = false;
        console.log(err);
      });
    },
    /**
   * 枚举合同审批所有类型(与待办中心类型一致)
   [0, '合同审批'],
  [1, '供应商结算'],
  [6, '精力分配'],
  [7, '签约内审'],
  [9, '申请原件'],
  [10, '开票申请'],
  [11, '发票作废'],
  [13, '还款申请'],
  [14, '员工报销'],
  [15, '借款申请']
  * */
    // 每个模块的loading键名
    loadingKeyMap(approvalModuleType) {
      return {
        0: 'listLoading',
        1: 'listLoading',
        6: 'infoLoading',
        7: 'infoLoading',
        9: 'infoLoading',
        10: 'pageLoading',
        11: 'infoLoading',
        13: 'infoLoading',
        14: 'pageLoading',
        15: 'infoLoading'
      }[approvalModuleType] || 'infoLoading';
    },
    setCurrentVersion(isCurrentVersion = true) {
      this.isCurrentVersion = isCurrentVersion;
    },
    // 切换审批单(付款申请、合同审批)
    handleToggleProcess(toggleType, processType) {
      let currentId;
      let businessType;
      if (this.$route.name === 'contractDetail') {
        currentId = this.contractId;
        businessType = BUSINESS_TYPE.CONTRACT;
      }
      if (this.$route.name === 'supplierDetail') {
        currentId = this.settleId;
        businessType = BUSINESS_TYPE.SETTLE;
      }
      // 传给服务端的唯一值，第一次前端生成，非第一次切换（即一直停留在当前详情页里切换）使用接口返回缓存值，离开详情页时在beforeRouterLeave清除缓存
      const cacheKey = this.sessionCacheKey || new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      const params = {
        toggleType,
        businessType,
        processId: Number(this.processId) || Number(this.workFlowId),
        filterData: this.getFilterObj(processType),
        currentId,
        cacheKey
      };
      if (this.$route.name === 'supplierDetail') {
        const supplierDimension = JSON.parse(localStorage.getItem('supplierDimension'));
        params.dataType = supplierDimension ? 2 : 1;
      }
      getToggleInfo(params).then(res => {
        if (res.code === 200) {
          if (res.data.finished) {
            this.$message.warning(toggleType ? '已经是最后一条审批单了' : '已经是最新的审批单了');
            return;
          }
          if (res.data.cacheKey) {
            sessionStorage.setItem(this.toggleKeyName, res.data.cacheKey);
          }
          this.goNextApproveDetail && this.goNextApproveDetail(res.data);
        }
      }).catch(err => console.error(err.message));
    },
    // 根据审批详情接口返回的processId判断当前审批页面的流程是否变动然后进行重定向操作
    handleProcessCheck(processId) {
      if (this.processId !== processId) {
        const { query, params, name } = this.$route;
        let newProcessId;
        if (!query.processId) {
          newProcessId = isNaN(Number(processId)) ? encryption(processId) : processId;
        } else {
          newProcessId = isNaN(Number(query.processId)) ? encryption(processId) : processId;
        }
        this.$router.replace({
          name,
          query: {
            ...query,
            processId: newProcessId
          },
          params
        });
      }
    }
  }
};
